package com.igeek.collateral.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @Author chenmin
 * @Description TODO
 */
public class JwtHelper {

    private static long tokenExpiration = 24*60*60*1000;
    private static String tokenSignKey = "com.igeek.health.aGVhbHRoMTIz";

    //生成Token
    public static String createToken(Integer memberId, String memberName) {
        String token = Jwts.builder()
                .setSubject("HEALTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("memberId", memberId)
                .claim("memberName", memberName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //通过token获取用户ID
    public static Integer getMemberId(String token) {
        if(StringUtils.hasLength(token)){
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer)claims.get("memberId");
            return userId;
        }
        return null;
    }

    //通过token获取用户姓名
    public static String getMemberName(String token) {
        if(StringUtils.hasLength(token)){
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String)claims.get("memberName");
        }
        return null;
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(1, "55");
        //eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJS8nB19Anx0A0Ndg1S0lFKrShQsjI0NzCyNDQwtzDRUcpNzU1KLfJMAYrCOH6JualAjaamSrUAIHZeTEUAAAA.0fvKvqQ2a2dRXDsKIx71j6KtdFo81fH8xTSkWEuZBoTnXiHmgcpT1d5QLGbc-BMwDzWp8LeT5QK1v2DRxqivSA
        System.out.println(token);
        System.out.println(JwtHelper.getMemberId(token));
        System.out.println(JwtHelper.getMemberName(token));
    }

}
